package com.work.formaldehyde.activity;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.transition.Slide;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.wang.avi.AVLoadingIndicatorView;
import com.work.formaldehyde.R;
import com.work.formaldehyde.model.MoRenDiZhiModel;
import com.work.formaldehyde.model.UserModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.OkHttp;
import com.work.formaldehyde.util.Url;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText edit_phone, edit_post;

    private int submit = 0, soup = 0;

    private RelativeLayout submit_user, get_soupt;
    private ImageView comeback;

    private LinearLayout pwd_login, zuida;

    private TextView spottext;
    private TextView yonghuxieyi, yinsizhengce;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 0);
        setContentView(R.layout.activity_userlogin);
        inti();
    }

    private InputMethodManager imm;
    private boolean isOpen;

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        isOpen = imm.isActive();
        pwd_login = findViewById(R.id.pwd_login);
        pwd_login.setOnClickListener(this);
        edit_post = findViewById(R.id.edit_post);
        spottext = findViewById(R.id.spottext);
        comeback = findViewById(R.id.title_comeback);
        comeback.setOnClickListener(this);
        edit_phone = findViewById(R.id.edit_phone);
        yonghuxieyi = findViewById(R.id.yonghuxieyi);
        yonghuxieyi.setOnClickListener(this);
        yinsizhengce = findViewById(R.id.yinsizhengce);
        yinsizhengce.setOnClickListener(this);
        submit_user = findViewById(R.id.submit_user);
        submit_user.setOnClickListener(this);
        get_soupt = findViewById(R.id.get_soupt);
        get_soupt.setOnClickListener(this);
        zuida = findViewById(R.id.zuida);
        zuida.setOnClickListener(this);
        edit_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!charSequence.toString().equals("")) {
                    submit_user.setBackgroundResource(R.drawable.rela_selected_bg_blue);
                    submit = 1;
                } else {
                    submit_user.setBackgroundResource(R.drawable.rela_selected_bg_huise);
                    submit = 0;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        getcodtime();
    }

    private Handler handler = new Handler();
    private Runnable runnable;
    private int tiemid = 60, setpost = 0;

    public void getcodtime() {
        runnable = new Runnable() {
            public void run() {
                if (tiemid == 0) {
                    StopTime();
                } else {
                    tiemid--;
                    spottext.setText(tiemid + "秒后获取");
                    handler.postDelayed(this, 1000);
                }
            }
        };
    }

    public void StopTime() {
        setpost = 0;
        tiemid = 60;
        handler.removeCallbacks(runnable);
        spottext.setText("获取验证码");
    }

    private String phonenum;
    private String codes;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pwd_login:
                if (isOpen)
                    imm.hideSoftInputFromWindow(edit_phone.getWindowToken(), 0);
                break;
            case R.id.title_comeback:
                onBackPressed();
                break;
            case R.id.get_soupt:
                phonenum = edit_phone.getText().toString();
                if (phonenum.length() != 11) {
                    ApiUtils.SetToast(LoginActivity.this, "手机号码有误");
                } else if (!ApiUtils.isPhoneNumber(phonenum)) {
                    ApiUtils.SetToast(LoginActivity.this, "手机号码有误");
                } else {
                    if (ApiUtils.isNetworkConnected(LoginActivity.this)) {
                        if (setpost == 0) {
                            okHttp_postFromParameters(0);
                            handler.postDelayed(runnable, 1000);
                            setpost = 1;
                        }
                    } else {
                        ApiUtils.SetToast(LoginActivity.this, "当前无网络连接");
                    }
                }
                break;
            case R.id.zuida:
                if (isOpen) {
                    imm.hideSoftInputFromWindow(edit_phone.getWindowToken(), 0);
                }
                break;
            case R.id.yonghuxieyi:
                Intent yhxy = new Intent(LoginActivity.this, YongHuXieYiActivity.class);
                startActivity(yhxy, ActivityOptions.makeSceneTransitionAnimation(LoginActivity.this).toBundle());
                break;

            case R.id.yinsizhengce:
                Intent yszc = new Intent(LoginActivity.this, YinSiActivity.class);
                startActivity(yszc, ActivityOptions.makeSceneTransitionAnimation(LoginActivity.this).toBundle());
                break;
            case R.id.submit_user:
                if (submit == 1) {
                    phonenum = edit_phone.getText().toString();
                    codes = edit_post.getText().toString();
                    if (phonenum.length() != 11) {
                        ApiUtils.SetToast(LoginActivity.this, "手机号码有误");
                    } else if (!ApiUtils.isPhoneNumber(phonenum)) {
                        ApiUtils.SetToast(LoginActivity.this, "手机号码有误");
                    } else if (codes.length() < 4 || codes.equals("")) {
                        ApiUtils.SetToast(LoginActivity.this, "验证码有误");
                    } else {
                        if (ApiUtils.isNetworkConnected(LoginActivity.this)) {
                            if (isOpen)
                                imm.hideSoftInputFromWindow(edit_phone.getWindowToken(), 0);
                            ApiUtils.windows(LoginActivity.this, get_soupt, "登录中~~");
                            new Handler().postDelayed(new Runnable() {
                                public void run() {
                                    ApiUtils.closepopup();
                                }
                            }, 10000);
                            okHttp_postFromParameters(1);
                        } else {
                            ApiUtils.SetToast(LoginActivity.this, "当前无网络连接");
                        }
                    }
                }
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ApiUtils.popupWindows != null && ApiUtils.popupWindows.isShowing()) {
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    private UserModel userm;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;

//    private void okHttp_postFromParameters(final int code) {
////        new Thread(new Runnable() {
////            @Override
////            public void run() {
////                try {
////                    OkHttpClient okHttpClient = new OkHttpClient();
////                    if (code == 0) {
////                        RequestBody formBody = new FormBody.Builder().add("phone", phonenum)
////                                .build();
////                        Request request = new Request.Builder().url(Url.GETCODE).post(formBody).build();
////                        okhttp3.Response response = okHttpClient.newCall(request).execute();
////                    } else {
////                        RequestBody formBody = new FormBody.Builder().add("phone", phonenum).add("code", codes)
////                                .build();
////                        Request request = new Request.Builder().url(Url.USERLOGIN).post(formBody).build();
////                        okhttp3.Response response = okHttpClient.newCall(request).execute();
////                        String msg = response.body().string();
////                        Message message = new Message();
////                        message.obj = msg;
////                        gethot.sendMessage(message);
////                    }
////                } catch (
////                        Exception e) {
////                    e.printStackTrace();
////                }
////            }
////        }).
////                start();
////    }

    private void okHttp_postFromParameters(final int code) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    if (code == 0) {
                        RequestBody formBody = new FormBody.Builder().add("phone", phonenum)
                                .build();
                        Request request = new Request.Builder().url(Url.GETLOGINCODE).post(formBody).build();
                        okhttp3.Response response = okHttpClient.newCall(request).execute();
                        String msg = response.body().string();
                    } else {
                        RequestBody formBody = new FormBody.Builder().add("phone", phonenum).add("code", codes)
                                .build();
                        Request request = new Request.Builder().url(Url.USERLOGINS).post(formBody).build();
                        okhttp3.Response response = okHttpClient.newCall(request).execute();
                        String msg = response.body().string();
                        Message message = new Message();
                        message.obj = msg;
                        gethot.sendMessage(message);
                    }
                } catch (
                        Exception e) {
                    ApiUtils.SetLog("E:" + e.toString());
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot = new Handler() {
        public void handleMessage(android.os.Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                ApiUtils.SetLog("msg="+msg.obj.toString());
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    ApiUtils.closepopup();
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        userm = gson.fromJson(msg.obj.toString(),
                                UserModel.class);
                        mSharedPreferences = getSharedPreferences("user", MODE_PRIVATE);  //名称和类型
                        mEditor = mSharedPreferences.edit();
                        mEditor.putString("user_id", userm.getData().getUser_id());
                        Url.USER_ID = userm.getData().getUser_id();
                        mEditor.putString("user_name", userm.getData().getUser_name());
                        Url.USER_NAME = userm.getData().getUser_name();
                        mEditor.putString("user_pwd", userm.getData().getUser_pwd());
                        mEditor.putString("user_phone", userm.getData().getUser_phone());
                        Url.USER_PHONE_NAME = userm.getData().getUser_name();
                        mEditor.putString("user_wechat", userm.getData().getUser_wechat());
                        Url.USER_WECHAT_NAME = userm.getData().getUser_wechat();
                        mEditor.putString("user_wechatpwd", userm.getData().getUser_wechatpwd());
                        mEditor.putString("user_zfb_zh", userm.getData().getUser_zfb_zh());
                        Url.USER_ALIPAY_NAME = userm.getData().getUser_zfb_zh();
                        mEditor.putString("user_zfb_name", userm.getData().getUser_zfb_name());
                        Url.USER_ALIPAY_USER_NAME = userm.getData().getUser_zfb_name();
                        mEditor.putString("user_nickname", userm.getData().getUser_nickname());
                        Url.USER_NICK_NAME = userm.getData().getUser_nickname();
                        mEditor.putString("user_head", userm.getData().getUser_head());
                        Url.USER_HEAD_IMG = userm.getData().getUser_head();
                        mEditor.putString("logintoken", userm.getData().getLogintoken());
                        Url.LOGIN_TOKEN = userm.getData().getLogintoken();
                        mEditor.apply();
                        mEditor.commit();
                        okHttp_postFromParameter();
                        onBackPressed();
                    } else
                        ApiUtils.SetToast(LoginActivity.this, msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void okHttp_postFromParameter() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody;
//                    Request request;
//                    formBody = new FormBody.Builder().add("uid", Url.USER_ID)
//                            .build();
//                    request = new Request.Builder().url(Url.GETMORENDIZHI).post(formBody).build();
//                    okhttp3.Response response = okHttpClient.newCall(request).execute();
//                    String msg = response.body().string();
//                    Message message = new Message();
//                    message.obj = msg;
//                    gethot1s.sendMessage(message);
                    Request request = new Request.Builder().get().url(Url.MORENADDRESS + Url.USER_ID+"&logintoken="+Url.LOGIN_TOKEN).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, final Response response) {
                            try {
                                final String responseStr;
                                responseStr = response.body().string();
                                Message message = new Message();
                                message.obj = responseStr;
                                gethot1s.sendMessage(message);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    MoRenDiZhiModel shangPingModel;
    public Handler gethot1s = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        shangPingModel = gson.fromJson(msg.obj.toString(),
                                MoRenDiZhiModel.class);
                        Url.MORENDIZHI = shangPingModel.getData().getConsignee_addr();
                        Url.MORENNAME = shangPingModel.getData().getConsignee_name();
                        Url.MORENPHONE = shangPingModel.getData().getConsignee_phone();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


}
